package com.group02.community.log;




import com.group02.community.entity.log.SysLogininfor;
import com.group02.community.service.SysLogininforService;
import com.group02.community.utils.JwtUtil;
import com.group02.community.utils.RsaUtil;
import com.group02.community.utils.log.IpUrl;
import com.group02.community.utils.log.SpringUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Log日志输出切面
 */
@Slf4j
@Aspect
@Component
public class LoginLog {

    /*登入日志*/
    @After("execution(* com.group02.community.controller.UserController.*(..))")
    public void login() throws IOException {
        //获取上下文请求
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取请求对象
        HttpServletRequest request = attr.getRequest();
        //输出日志
//        log.info("当前用户"+request.getRemoteUser());
//        log.info("登录地址:"+request.getServerName());
//        log.info("登录地点:"+ IpUrl.ip());
//        log.info("浏览器:"+UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser());
        log.info("操作系统的名称：" + System.getProperties().getProperty("os.name"));
        SysLogininfor sysLogininfor = null;
        String userName = request.getRemoteUser();
        String ipAddr = request.getServerName();
        String loginLocation = "内网IP";
        String browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser().toString();
        String toLowerCase = browser.substring(1,browser.length()).toLowerCase();
        String browserToUpperCaseFirstOne = browser.substring(0,1)+toLowerCase;
        String os = System.getProperties().getProperty("os.name");
        String status = "";
        String msg = "";
        //当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String loginTime = formatter.format(date);
        sysLogininfor = new SysLogininfor();
        try {
            loginLocation = IpUrl.ip();
            status = "0";
            msg = "登录成功";
        } catch (RuntimeException e) {
            status = "1";
            msg = "登录超时";
            e.printStackTrace();
        } finally {
            sysLogininfor.setUserName(userName);
            sysLogininfor.setIpaddr(ipAddr);
            sysLogininfor.setLoginLocation(loginLocation);
            sysLogininfor.setBrowser(browserToUpperCaseFirstOne);
            sysLogininfor.setOs(os);
            sysLogininfor.setStatus(status);
            sysLogininfor.setMsg(msg);
            sysLogininfor.setLoginTime(loginTime);
            SpringUtils.getBean(SysLogininforService.class).insertLogininfor(sysLogininfor);
        }
    }

    @After("execution(* com.group02.community.config.LogoutSuccessHandler.onLogoutSuccess(..))")
    public void logout() throws IOException {
        //获取上下文请求
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取请求对象
        HttpServletRequest request = attr.getRequest();
        //输出日志
//        log.info("当前用户"+request.getRemoteUser());
//        log.info("登录地址:"+request.getServerName());
//        log.info("登录地点:"+ IpUrl.ip());
//        log.info("浏览器:"+UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser());
        log.info("操作系统的名称：" + System.getProperties().getProperty("os.name"));
        SysLogininfor sysLogininfor = null;
        String token = request.getHeader("Authorization");
        String userName = JwtUtil.getUsernameFromToken(token, RsaUtil.publicKey);
//        String userName = request.getRemoteUser();
        String ipAddr = request.getServerName();
        String loginLocation = "内网IP";
        String browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser().toString();
        String toLowerCase = browser.substring(1,browser.length()).toLowerCase();
        String browserToUpperCaseFirstOne = browser.substring(0,1)+toLowerCase;
        String os = System.getProperties().getProperty("os.name");
        String status = "";
        String msg = "";
        //当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String loginTime = formatter.format(date);
        sysLogininfor = new SysLogininfor();
        try {
            loginLocation = IpUrl.ip();
            status = "0";
            msg = "退出成功";
        } catch (RuntimeException e) {
            status = "1";
            msg = "退出超时";
            e.printStackTrace();
        } finally {
            sysLogininfor.setUserName(userName);
            sysLogininfor.setIpaddr(ipAddr);
            sysLogininfor.setLoginLocation(loginLocation);
            sysLogininfor.setBrowser(browserToUpperCaseFirstOne);
            sysLogininfor.setOs(os);
            sysLogininfor.setStatus(status);
            sysLogininfor.setMsg(msg);
            sysLogininfor.setLoginTime(loginTime);
            SpringUtils.getBean(SysLogininforService.class).insertLogininfor(sysLogininfor);
        }
        request.getSession().removeAttribute("username");
    }

    //配置环绕通知
    @Around("execution(* com.group02.community.controller.*Controller.*(..))")
    public Object aroundLog(ProceedingJoinPoint point) throws Throwable {
        //记录方法执行前时间
        long start = System.currentTimeMillis();
        //打印方法名称
        log.info("当前执行方法：" + point.getSignature().getName());
        //打印参数
        Object[] args = point.getArgs();
        for(Object arg : args){
            log.info("参数："+arg);
        }
        //打印返回值
        Object result = point.proceed();
        if(log.isDebugEnabled()){
            log.info("方法返回值：" +result);
        }
        //打印执行时间
        long end = System.currentTimeMillis();
        log.info("方法执行时间：" +(end - start));
        return result;
    }

    //配置环绕通知
//    @Around("execution(* cn.xl.intelligence_community.controller.*Controller.add*(..)) || " +
//            "execution(* cn.xl.intelligence_community.controller.*Controller.update*(..))")
//    public Object aroundAddUpdate(ProceedingJoinPoint point) throws Throwable {
//        //获得切中方法的所有参数
//        Object[] args = point.getArgs();
//        for(Object arg : args){
//            //获得每个参数的setXX
//            Method setAge = arg.getClass().getDeclaredMethod("setAge", Integer.class);
//            if(setAge != null){
//                //调用方法设置默认值
//                setAge.invoke(arg,18);
//                log.info("设置age为18");
//            }
//        }
//        Object result = point.proceed();
//        return result;
//    }


}
